package com.wkm.chainchain.deprecated_buildmock;

import com.alibaba.fastjson.JSON;
import com.wkm.chainchain.pbft.common.MyThreadPoolExecutor;
import com.wkm.chainchain.pbft.common.PBFTMsgType;
import com.wkm.chainchain.pbft.msg.PBFTMsg;
import com.wkm.chainchain.pbft.p2p.PBFTClient;
import com.wkm.chainchain.websocket.Client;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;

public class MsgClient implements Runnable {

    private final CountDownLatch SERVER_NODE_LATCH;
    private final CountDownLatch NODE_CONNECTED_LATCH;
    private final int CLIENT_PORT;
    private final int INITIAL_PORT;

    public MsgClient(CountDownLatch serverNodeLatch, CountDownLatch nodeConnectedLatch, int CLIENT_PORT, int INITIAL_PORT) {
        this.SERVER_NODE_LATCH = serverNodeLatch;
        this.NODE_CONNECTED_LATCH = nodeConnectedLatch;
        this.CLIENT_PORT = CLIENT_PORT;
        this.INITIAL_PORT = INITIAL_PORT;
    }

    @Override
    public void run() {

        // 等待主节点启动后，再往下执行
        try {
            SERVER_NODE_LATCH.await();
            System.out.println("主节点已经启动！");
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }

        Client client = PBFTClient.getInstance();
        //与主节点建立连接
        client.connectPeer("ws://localhost:" + INITIAL_PORT);

        // 等待所有服务端节点连接完成，再往下执行
        try {
            NODE_CONNECTED_LATCH.await();
            System.out.println("所有服务端节点连接完成，再往下执行！");
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }

        //创建线程发送消息
        MyThreadPoolExecutor.threadPoolExecutor.execute(() -> {
            for (int i = 0; i < 1; i++) {
                PBFTMsg pbftMsg = new PBFTMsg();
                pbftMsg.setMsgType(PBFTMsgType.REQUEST.getCode());
                pbftMsg.setViewIndex(0);
                pbftMsg.setMsgIndex((long) i);
                pbftMsg.setMessage(UUID.randomUUID().toString());
                client.broadcast(JSON.toJSONString(pbftMsg));
            }
        });
    }
}
